<?php

namespace app\admin\controller;

use app\common\controller\AdminController;
use app\common\model\CompanyWarehouse;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\Request;
use Exception;
use think\App;
use think\response\Json;

/**
 * @ControllerAnnotation(title="仓库管理")
 */
class Warehouse extends AdminController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new CompanyWarehouse();
    }

    /**
     * @NodeAnnotation (title="列表")
     */
    public function list(): Json
    {
        // 组合查询参数
        list($limit, $where) = $this->buildSearchParams();
        // 获取列表数据
        $sql = $this->model->whereIn('company_id', $this->companyIds);
        $list = $sql->with(['company'])->where($where)->order($this->sort)->paginate($limit);
        if ($this->each) $list = $this->each($list);
        return $this->success($list);
    }

    /**
     * @NodeAnnotation (title="新增")
     */
    public function add(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $this->sceneValidate($post, 'add');
        if (!isValidLatLng($post['lat']??'', $post['lon']??'')) return $this->error('经纬度填写不合法！');
        if (!empty($this->groupId)) $post['group_id'] = $this->groupId;
        if (!empty($this->companyId)) $post['company_id'] = $this->companyId;
        $post['product_amount'] = $post['product_amount'] ?? 0.00;
        if(getMoneyLength($post['product_amount']) > 8) return $this->error('产品金额字段过长！');
        $post['no'] = generateOrderNo('CK');
        try {
            $this->model->transaction(function () use ($post)
            {
                $this->model->save($post);
            });
        } catch (Exception $e) {
            return $this->error('新增失败:' . $e->getMessage());
        }
        return $this->success('新增成功');
    }
}